#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>

int main(){
  extern char** environ;
  putenv("PRIVATE_ENV=6666666");
  //单进程替换
  //printf("before:I'm a process,pid:%d,ppid:%d\n",getpid(),getppid());

  //这类方法的标准写法
  //execl("/usr/bin/ls","ls","-a","-l",NULL);//结尾必须以NULL结尾
  //execl("/usr/bin/top","top",NULL);
  
  //printf("after:I'm a process,pid:%d,ppid:%d\n",getpid(),getppid());

  //多进程替换
  pid_t id=fork();
  if(id==0){
    //子进程
   //char* const myargv[]={
   //  "ls",
   //  "-l",
   //  "-a",
   //  NULL
   //};
    printf("before:I'm a process,pid:%d,ppid:%d\n",getpid(),getppid());
    //sleep(5);
    //这类方法的标准写法
    //execlp("ls","-a","-l",NULL);//结尾必须以NULL结尾
    //execl("/usr/bin/top","top",NULL);
    //execv("/usr/bin/ls",myargv);
    //execvp("ls",myargv);
    char* const myargv[]={
      "otherExe",
      "-a",
      "-b",
      "-c",
      NULL
    };
    char* const myenv[]={
      "MYVAL=1111",
      "MYPATH=/usr/bin/XXX",
      NULL
    };
    //不在使用系统的环境变量
    execle("./otherExe","otherExe","-a","-w","-v",NULL,myenv);
    //execv("./otherExe",myargv);//第一个参数代表可以调用当前路径下的程序
    //execl("/usr/bin/bash","bash","test.sh",NULL);//第一个参数代表可以调用当前路径下的程序

    //如果代码能运行到这里说明execl函数并没有执行成功
    printf("after:I'm a process,pid:%d,ppid:%d\n",getpid(),getppid());
    exit(0);//为了不让子进程继续往后运行
  }
  //父进程
  pid_t ret=waitpid(id,NULL,0);
  if(ret>0){
    printf("wait success,father pid:%d,child pid:%d\n",getpid(),ret);
  }
  sleep(5);

  return 0;
}
